<template>
  <a-spin :spinning="confirmLoading">
    <j-form-container :disabled="formDisabled">
      <!-- 主表单区域 -->
      <a-form-model ref="form" :model="model" :rules="validatorRules" slot="detail">
        <a-row>
          <a-col :xs="24" :sm="12">
            <a-form-model-item
              label="申请订单编码"
              :labelCol="labelCol"
              :wrapperCol="wrapperCol"
              prop="code"
            >
              <a-input v-model="model.code" placeholder="请输入申请订单编码" disabled></a-input>
            </a-form-model-item>
          </a-col>
          <a-col :xs="24" :sm="12">
            <a-form-model-item
              label="需求方所处公司"
              :labelCol="labelCol"
              :wrapperCol="wrapperCol"
              prop="demandCompany"
            >
              <j-select-depart v-model="model.demandCompany" :multi="true" />
            </a-form-model-item>
          </a-col>
          <a-col :xs="24" :sm="12">
            <a-form-model-item
              label="需求方所处部门"
              :labelCol="labelCol"
              :wrapperCol="wrapperCol"
              prop="demandDepartment"
            >
              <j-select-depart v-model="model.demandDepartment" :multi="true" />
            </a-form-model-item>
          </a-col>
          <a-col :xs="24" :sm="12">
            <a-form-model-item
              label="申请部门"
              :labelCol="labelCol"
              :wrapperCol="wrapperCol"
              prop="department"
            >
              <j-select-depart v-model="model.department" :multi="true" />
            </a-form-model-item>
          </a-col>
          <a-col :xs="24" :sm="12">
            <a-form-model-item
              label="申请人"
              :labelCol="labelCol"
              :wrapperCol="wrapperCol"
              prop="personnel"
            >
              <j-select-user-by-dep v-model="model.personnel" :multi="true" />
            </a-form-model-item>
          </a-col>
          <a-col :xs="24" :sm="12">
            <a-form-model-item
              label="采购类型"
              :labelCol="labelCol"
              :wrapperCol="wrapperCol"
              prop="orderType"
            >
              <j-dict-select-tag
                type="list"
                v-model="model.orderType"
                dictCode="purchase_order_type"
                placeholder="请选择采购类型"
              />
            </a-form-model-item>
          </a-col>
          <a-col :xs="24" :sm="12">
            <a-form-model-item
              label="物品或礼品"
              :labelCol="labelCol"
              :wrapperCol="wrapperCol"
              prop="goodsOrGift"
            >
              <j-dict-select-tag
                type="radio"
                v-model="model.goodsOrGift"
                dictCode="purchase_goods_gift"
                placeholder="请选择物品或礼品"
              />
            </a-form-model-item>
          </a-col>
          <a-col :xs="24" :sm="12">
            <a-form-model-item
              label="申请日期"
              :labelCol="labelCol"
              :wrapperCol="wrapperCol"
              prop="orderDate"
            >
              <j-date placeholder="请选择申请日期" v-model="model.orderDate" style="width: 100%" />
            </a-form-model-item>
          </a-col>
          <a-col :xs="24" :sm="12">
            <a-form-model-item
              label="申请原因"
              :labelCol="labelCol"
              :wrapperCol="wrapperCol"
              prop="reason"
            >
              <a-textarea v-model="model.reason" v-decorator="['reason']" rows="4" placeholder="请输入申请原因" />
            </a-form-model-item>
          </a-col>
          <a-col :xs="24" :sm="12">
            <a-form-model-item
              label="备注"
              :labelCol="labelCol"
              :wrapperCol="wrapperCol"
              prop="remark"
            >
              <a-textarea v-model="model.remark" v-decorator="['remark']" rows="4" placeholder="请输入备注" />
            </a-form-model-item>
          </a-col>
          <a-col :xs="24" :sm="12">
            <a-form-model-item
              label="附件"
              :labelCol="labelCol"
              :wrapperCol="wrapperCol"
              prop="attachment"
            >
              <j-upload v-model="model.attachment" :number="10" :before-upload="beforeUpload"></j-upload>
            </a-form-model-item>
          </a-col>
          <a-col :xs="24" :sm="12">
            <a-form-model-item
              label="总计金额"
              :labelCol="labelCol"
              :wrapperCol="wrapperCol"
              prop="total"
            >
              <a-input-number v-model="model.total" style="width: 100%" disabled/>
            </a-form-model-item>
          </a-col>
        </a-row>
      </a-form-model>
    </j-form-container>
    <!-- 子表单区域 -->
    <a-tabs v-model="activeKey" @change="handleChangeTabs">
      <a-tab-pane tab="申请的物品" :key="refKeys[0]" :forceRender="true">
        <j-editable-table
          :ref="refKeys[0]"
          :loading="purchaseOrderItemTable.loading"
          :columns="purchaseOrderItemTable.columns"
          :dataSource="purchaseOrderItemTable.dataSource"
          :maxHeight="300"
          :disabled="formDisabled"
          :rowNumber="true"
          :rowSelection="true"
          :actionButton="true"
          @valueChange="valueChange"
        >
        </j-editable-table>
      </a-tab-pane>
    </a-tabs>
  </a-spin>
</template>

<script>
import { FormTypes, getRefPromise, VALIDATE_NO_PASSED } from '@/utils/JEditableTableUtil'
import { JEditableTableModelMixin } from '@/mixins/JEditableTableModelMixin'
import { validateDuplicateValue } from '@/utils/util'
import { orderCodeRule } from '@/api/api'
import currency from 'currency.js'

export default {
  name: 'PurchaseOrderForm',
  mixins: [JEditableTableModelMixin],
  components: {},
  data() {
    return {
      labelCol: {
        xs: { span: 24 },
        sm: { span: 5 }
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 16 }
      },
      model: {
        code: ''
      },
      validatorRules: {
        demandCompany: [
            { required: true, message: '请选择需求方所处公司'},
            // { min: 1, max: 50, message: '长度在1到50个字符', tigger: 'blur'}
          ],
          demandDepartment: [
            { required: true, message: '请选择需求方所处部门'},
          ],
          department: [
            { required: true, message: '请选择申请部门'},
          ],
          labelCol: [
            { required: true, message: '请选择申请人'},
          ],
          orderType: [
            { required: true, message: '请选择采购类型'},
          ],
          goodsOrGift: [
            { required: true, message: '请选择物品或礼品'},
          ],
          orderDate: [
            { required: true, message: '请选择申请日期'},
          ],
          reason: [
            { required: true, message: '请输入申请原因'},
          ],
      },
      // 新增时子表默认添加几行空数据
      addDefaultRowNum: 1,
      refKeys: ['purchaseOrderItem'],
      tableKeys: ['purchaseOrderItem'],
      activeKey: 'purchaseOrderItem',
      // 申请的物品
      purchaseOrderItemTable: {
        loading: false,
        dataSource: [],
        columns: [
          {
            title: '供应商编码',
            key: 'providerCode',
            type: FormTypes.popup,
            popupCode: 'purchase_provider',
            destFields: 'providerCode,providerName',
            orgFields: 'code,name',
            width: '200px',
            placeholder: '请输入${title}',
            defaultValue: '',
            validateRules: [{ required: true, message: '请输入${title}'},],
          },
          {
            title: '供应商',
            key: 'providerName',
            type: FormTypes.input,
            disabled: true,
            width: '200px',
            placeholder: '请输入${title}',
            defaultValue: ''
          },
          {
            title: '产品编码',
            key: 'goodsCode',
            type: FormTypes.popup,
            popupCode: 'purchase_goods',
            destFields: 'goodsCode,goodsTypeCode,goodsName,unit,goodsBrand,size,unitPrice',
            orgFields: 'code,goods_type_code,goods_name,unit,brand,size,unit_price',
            width: '200px',
            placeholder: '请输入${title}',
            defaultValue: '',
            validateRules: [{ required: true, message: '请输入${title}'},],
          },
          {
            title: '产品分类',
            key: 'goodsTypeCode',
            type: FormTypes.select,
            dictCode: 'purchase_goods_type',
            disabled: true,
            width: '200px',
            placeholder: '请输入${title}',
            defaultValue: ''
          },
          {
            title: '产品名称',
            key: 'goodsName',
            type: FormTypes.input,
            disabled: true,
            width: '200px',
            placeholder: '请输入${title}',
            defaultValue: ''
          },
          {
            title: '单位',
            key: 'unit',
            type: FormTypes.select,
            dictCode: 'purchase_unit',
            disabled: true,
            width: '200px',
            placeholder: '请输入${title}',
            defaultValue: ''
          },
          {
            title: '品牌',
            key: 'goodsBrand',
            type: FormTypes.input,
            disabled: true,
            width: '200px',
            placeholder: '请输入${title}',
            defaultValue: ''
          },
          {
            title: '规格/尺寸/型号',
            key: 'size',
            type: FormTypes.input,
            disabled: true,
            width: '200px',
            placeholder: '请输入${title}',
            defaultValue: ''
          },
          {
            title: '单价',
            key: 'unitPrice',
            type: FormTypes.inputNumber,
            width: '200px',
            placeholder: '请输入${title}',
            defaultValue: '',
            validateRules: [
              { required: true, message: '请输入${title}'},
              {pattern: /^\d+(\.{0,1}\d+){0,1}$/, message: '${title}必须非负数'}
            ],
          },
          {
            title: '数量',
            key: 'number',
            type: FormTypes.inputNumber,
            width: '200px',
            placeholder: '请输入${title}',
            defaultValue: '',
            validateRules: [{ required: true, message: '请输入${title}'},],
          },
          {
            title: '小计',
            key: 'total',
            type: FormTypes.inputNumber,
            disabled: true,
            width: '200px',
            placeholder: '请输入${title}',
            defaultValue: '',
          },
          {
            title: '附件',
            key: 'attachment',
            type: FormTypes.file,
            token: true,
            responseName: 'message',
            number: 10,
            width: '200px',
            placeholder: '请选择文件',
            defaultValue: '',
          },

          {
            title: 'provider_code',
            key: 'provider_code',
            type: 'hidden'
          },

          {
            title: 'provider_name',
            key: 'provider_name',
            type: 'hidden'
          },

          {
            title: 'goods_code',
            key: 'goods_code',
            type: 'hidden'
          },

          {
            title: 'goods_type_code',
            key: 'goods_type_code',
            type: 'hidden'
          },

          {
            title: 'goods_name',
            key: 'goods_name',
            type: 'hidden'
          },

          {
            title: 'goods_brand',
            key: 'goods_brand',
            type: 'hidden'
          },

          {
            title: 'unit_price',
            key: 'unit_price',
            type: 'hidden'
          }
        ]
      },
      url: {
        add: '/purchase/purchaseOrder/add',
        edit: '/purchase/purchaseOrder/edit',
        purchaseOrderItem: {
          list: '/purchase/purchaseOrder/queryPurchaseOrderItemByMainId'
        }
      }
    }
  },
  props: {
    //表单禁用
    disabled: {
      type: Boolean,
      default: false,
      required: false
    }
  },
  computed: {
    formDisabled() {
      return this.disabled
    }
  },
  created() {
  },
  methods: {
    valueChange(obj){
      // console.log(obj)
      if(obj.row.unitPrice >=0 && obj.row.number >= 0){
        // let sub_total = obj.row.unitPrice * obj.row.number
        let sub_total = currency(obj.row.unitPrice).multiply(obj.row.number)
          if(sub_total != obj.row.total){
            obj.target.setValues([{
              rowKey: obj.row.id,
              values: {
                'total': sub_total
              }
            }])
          }
      }
      obj.target.getValues((error,values) => {
        let total = 0
          values.map(item => {
            // total += item.total
            total =currency(total).add(item.total)
          })
          console.log(total)
          this.model.total = total.value
      })
    },
    //初始化订单编码
    init() {
      orderCodeRule({}).then(res => {
        if (res.success) {
          this.model.code = res.result
        } else {
          this.$message.warning(res.message)
        }
      })
      // this.$refs.form.title="合同新增";
    },
    addBefore() {
      this.purchaseOrderItemTable.dataSource = []
    },
    getAllTable() {
      let values = this.tableKeys.map(key => getRefPromise(this, key))
      return Promise.all(values)
    },
    /** 调用完edit()方法之后会自动调用此方法 */
    editAfter() {
      this.$nextTick(() => {})
      // 加载子表数据
      if (this.model.id) {
        let params = { id: this.model.id }
        this.requestSubTableData(this.url.purchaseOrderItem.list, params, this.purchaseOrderItemTable)
      }
      if(!this.model.id){
          this.init();
        }
    },
    //校验所有一对一子表表单
    validateSubForm(allValues) {
      return new Promise((resolve, reject) => {
        Promise.all([])
          .then(() => {
            resolve(allValues)
          })
          .catch(e => {
            if (e.error === VALIDATE_NO_PASSED) {
              // 如果有未通过表单验证的子表，就自动跳转到它所在的tab
              this.activeKey = e.index == null ? this.activeKey : this.refKeys[e.index]
            } else {
              console.error(e)
            }
          })
      })
    },
    /** 整理成formData */
    classifyIntoFormData(allValues) {
      let main = Object.assign(this.model, allValues.formValue)

      return {
        ...main, // 展开
        purchaseOrderItemList: allValues.tablesValue[0].values
      }
    },
    validateError(msg) {
      this.$message.error(msg)
    },
    close() {
      this.visible = false
      this.$emit('close')
      this.$refs.form.clearValidate()
    },
    beforeUpload(file) {
      const isLt2M = file.size / 1024 / 1024 < 2;
      if (!isLt2M) {
        this.$message.error('文件过大');
      }
      const isMax = this.model.attachment && this.model.attachment.split(',').length >= 10
      if(isMax){
        this.$message.error('最多上传文件数10个');
      }
      return isLt2M && !isMax;
    },
  }
}
</script>

<style scoped>
</style>